<?php

class Validator_NotifyOfClientESChange extends Validator_Default {
    private $db;
    public function __construct($db) {
        $this->db = $db;
    }

    public function isValid($obj) {
        return $this->isValidClient($obj) && $this->isValidES($obj);
    }

	private function isValidClient($obj) {
        $clientValidator = new Validator_Client();
        if (!$clientValidator->isValid($obj->client)) {
            $this->error = $clientValidator->error;
            return false;
        }
        return true;
    }

	private function isValidES($obj) {
        $esValidator = new Validator_ES();
        if (!$esValidator->isValid($obj->newES)) {
            $this->error = $esValidator->error;
            return false;
        }
        if ($obj->oldES) {
            if (!$esValidator->isValid($obj->oldES)) {
                $this->error = $esValidator->error;
                return false;
            }
            if ($obj->oldES->id == $obj->newES->id) {
                $this->error = ES_ERROR_OLD_NEW_SAME;
                return false;
            }
        }
        $bind = new DB_ClientEnergySupplierBind($this->db);
        $currentBind = $bind->getCurrentRecord($obj->client->id);
        if ($currentBind && $currentBind['es_id'] == $obj->newES->id) {
            $this->error = ES_ERROR_NEW_ALREADY_ACTIVE;
            return false;
        }
        return true;
    }
}
